package ewa

import (
	"fmt"
	"encoding/json"
	//"github.com/garyburd/redigo/redis"
)


type Message struct {
	ApiPath string        `json:"ApiPath"`
	ClientIP string       `json:"ClientIP"`
	Scheme string 		`json:"Scheme"`
	XID string          `json:"XID"`
	Form interface{}    `json:"Form"`
}

func MessageContentBind(f interface{}) *Message {
	m := new(Message)
	m.Form = f
	return m
}

func MessageFormat(queue string, msg []interface{}, m *Message) *Message {
	if msg == nil{
		return nil
	}
	if string(msg[0].([]byte)) != queue {
		fmt.Errorf("message wrong: %v", msg[0])
	}else{
		//fmt.Println(msg[1])
		if err := json.Unmarshal(msg[1].([]byte), m); err != nil {
			fmt.Println(err)
			return nil
		}else{
			return m
		}
	}
	return nil
}

func MessagePrint(m *Message) {
	if m != nil {
		fmt.Printf("ApiPath: %s\n", m.ApiPath)
		fmt.Printf("ClientIP: %s\n", m.ClientIP)
		fmt.Printf("Scheme: %s\n", m.Scheme)

		fmt.Println(m.Form)
	}
}


func MessageBRPOP(RedisConnArgs_ RedisConnArgs, queue string, f interface{}, timeout int) *Message {
	c:=CreateRedisConn(RedisConnArgs_)
	m:=MessageContentBind(f)
	msg := RedisQbRPop(c, queue, timeout)
	MessageFormat(queue, msg, m)
	RemoveRedisConn(c)

	return m
}